package com.dgut.springsecurity.Adapter;

import com.dgut.springsecurity.Details.UserAccountDetailService;
import com.dgut.springsecurity.handler.UserLoginFailureHandler;
import com.dgut.springsecurity.handler.UserLoginSuccessHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;

import javax.annotation.Resource;

@Configuration
//@EnableWebSecurity
@Order(101)
public class UserAdapter extends WebSecurityConfigurerAdapter {

    @Resource
    private UserAccountDetailService userAccountDetailService;
    @Autowired
    private BCryptPasswordEncoder bCryptPasswordEncoder;
    @Resource
    private UserLoginSuccessHandler userLoginSuccessHandler;
    @Resource
    private UserLoginFailureHandler userLoginFailureHandler;
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userAccountDetailService).passwordEncoder(bCryptPasswordEncoder);

    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable();

        http
                .authorizeRequests()
                .antMatchers("/").permitAll()// 首页放行
                .antMatchers("/user/attribute").permitAll()
                .antMatchers("/user/registry_frontend").permitAll()
                .antMatchers("/user/add").permitAll()
                .antMatchers("/user/wx/getOpenId").permitAll()
                .antMatchers("/user/login_frontend").permitAll()
                .anyRequest().hasAnyAuthority("USER").and()
                .formLogin()
                .loginPage("/user/login_frontend").permitAll()

                //.defaultSuccessUrl("/user",true)
                //.successForwardUrl("/user")
                .successHandler(userLoginSuccessHandler)
                .failureHandler(userLoginFailureHandler).and()
                .logout()
                .logoutUrl("/user/logout").permitAll()
                .logoutSuccessUrl("/user/login_frontend?logout");

    }
}
